package pers.whj.sort;

public class BubbleSort<T> extends Sort<T> {
    public BubbleSort(T[] data) throws SortException {
        super(data);
    }

    public BubbleSort(T[] data, Compare<T> compare) throws SortException {
        super(data, compare);
    }

    @Override
    public void sort(int left, int right) throws SortException {
        sort(mData, mCompare, left, right);
    }

    public static <E> void sort(E[] data) throws SortException {
        sort(data, null);
    }

    public static <E> void sort(E[] data, Compare<E> compare) throws SortException {
        sort(data, compare, 0, data == null ? 0 : data.length - 1);
    }

    public static <E> void sort(E[] data, Compare<E> compare, int left, int right) throws SortException {
        check(data, compare, left, right);
        if (right - left >= 1) {
            boolean flag;
            for (int i = left + 1; i <= right; i++) {
                flag = false;
                for (int j = right; j >= i; j--) {
                    if (compare.swap(data[j - 1], data[j])) {
                        E temp = data[j - 1];
                        data[j - 1] = data[j];
                        data[j] = temp;
                        flag = true;
                    }
                }
                if (!flag) {
                    break;
                }
            }
        }
    }
}